<?php
/**
 * Arr.php
 * User: tommy
 */


namespace Svick\Helper;


class Arr
{
    /**
     * 深度合并
     *
     * @param $array
     * @param $tobe_merge_array
     */
    public static function deepmerge(&$array, $tobe_merge_array)
    {
        foreach ($tobe_merge_array as $key => $item) {
            if (is_array($item)) {
                if (isset($array[$key]) && is_array($array[$key])) {
                    //递归深度合并
                    self::deepmerge($array[$key], $item);
                } else {
                    $array[$key] = $item;
                }
            } else {
                $array[$key] = $item;
            }
        }
    }

    /**
     * 将数组转换为php代码
     *
     * @param $array
     * @param $level
     * @return string
     */
    public static function toPhpString($array, $deep = 1, $level = 0): string
    {
        $level ++;
        $strings = [];
        foreach ($array as $key => $value) {
            if (is_string($key)) {
                $key = "'" . addslashes($key) . "'";
            }

            if (is_array($value)) {
                $value = self::toPhpString($value, $deep, $level);
            } elseif (is_string($value)) {
                $value = "'" . addslashes($value) . "'";
            } elseif (is_bool($value)) {
                $value = $value ? 'true' : 'false';
            } elseif (is_null($value)) {
                $value = 'null';
            } elseif (is_int($value) || is_float($value)) {
                // Integers and floats are fine as they are
            } else {
                $value = var_export($value, true);
            }

            $strings[] = ($level > $deep ? '' : "\n" . str_repeat(' ', $level * 4)) . (is_string($key) ? "$key => $value" : $value);
        }

        return '[' . implode(', ', $strings) . ($level > $deep ? '' : "\n" . str_repeat(' ', ($level - 1) * 4)) . ']';
    }
}
